import { h } from 'vue'
import cache from './cache'
import router from './../router'
import store, { STORE_KEY } from '@store'
import { ElMessage } from 'element-plus'
import service from './../services'
import postscribe from 'postscribe'
import { imgSERVEURL } from './config'
const { body } = document
const WIDTH = 992 // refer to Bootstrap's responsive design

export const trans = (promise) => {
    return promise
        .then((data) => {
            return data
        })
        .catch((err) => {
            return err
        })
}

export default {
    getUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
        })
    },
    getBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => resolve(reader.result)
            reader.onerror = (error) => reject(error)
        })
    },
    isMobile() {
        const rect = body.getBoundingClientRect()
        return rect.width - 1 < WIDTH
    },
    loadJS(url, callback) {
        if (!url) return
        postscribe('#head', `<script src="${url}"></script>`, {
            done: function () {
                callback && callback()
            }
        })
    },
    isLogin() {
        return !!cache.get(cache.key.ACCESS_TOKEN)
    },
    toMoney(amount, divide = 100) {
        if (!amount) return 0
        if (amount % divide == 0) return amount / divide
        let money = amount / divide
        if (money < 1000) {
            return money.toFixed(2)
        }
        return money.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    async toLogin() {
        const res = await service.user.loginOut()
        if(res.resultCode == 8200){
            store.dispatch(STORE_KEY.A_CLEAR_TOKEN);
            router.replace('/login');
        }
        
        // let url = window.location.origin + window.location.pathname + '#/login'
        // window.location.replace(window.location.pathname + '#/login')
        // window.location.href = (window.location.pathname + '#/login')
    },
    /**
     *
     * @param {*} isPage true
     * @param {*} line //一般是table 上功能行数，一行41
     * @param {*} off //偏移，一般是table 上需要微调的部分
     * @param {*} full //是否是全屏的，也就是“main” 和 “main-white”的区别
     * @returns
     */
    tableHeight(isPage = true, line = 0, off = 0, full = false) {
        // if (document.body.clientHeight <= 600) {
        //     return 'auto'
        // }
        let height =
            document.body.clientHeight -
            88 -
            20 -
            8 -
            line * 42 -
            (full ? 0 : 10) -
            off -
            (isPage ? 44 : 0)
        return height
    },
    export(data, filename, isString = false) {
        let tData = data
        if (isString) {
            var bstr = atob(data),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            tData = u8arr
        }

        if (typeof window.chrome !== 'undefined') {
            // Chrome version
            let blob = new Blob([tData], { type: 'application/vnd.ms-excel' })
            var link = document.createElement('a')
            const url = URL.createObjectURL(blob)
            link.setAttribute('href', url)
            link.setAttribute('download', filename)
            link.click()
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE version
            let blob = new Blob([tData], { type: 'application/force-download' })
            window.navigator.msSaveBlob(blob, filename)
        } else {
            // Firefox version
            var file = new File([tData], filename, { type: 'application/vnd.ms-excel' })
            window.open(URL.createObjectURL(file))
        }
    },
    warning(messages) {
        let array = []
        messages.forEach((item) => {
            array.push(h('div', null, item))
        })
        ElMessage({
            type: 'error',
            message: h('div', { class: 'color-2' }, array)
        })
    },
    async push(path, query, name) {
        if (name) {
            setTimeout(() => {
                store.commit(STORE_KEY.M_DEL_VIEW, { name })
            }, 0)
        }
        router.push({ path, query })
    },
    async back(view) {
        store.commit(STORE_KEY.M_DEL_VIEW, view)
        const latestView = store.state.app.tagsView.visitedViews
            ? store.state.app.tagsView.visitedViews.slice(-1)[0]
            : null
        if (latestView) {
            router.push(latestView.fullPath)
        } else {
            router.push('/')
        }
    },
    clearRow(row) {
        for (var key in row) {
            if (key !== '_XID') {
                delete row[key]
            }
        }
    },
    async uploadFile(file, percentage) {
        let ossInfo = await service.sys.ossToken('magicmart')
        if (!ossInfo) {
            ElMessage.error('获取oss失败 请刷新重试')
            return null
        }
        let ftype = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
        let fname = `magic_${Date.parse(new Date())}`
        let fileName = `magic/${file.type.split('/')[0]}/${fname}.${ftype}` //定义唯一的文件名

        let client = new OSS({
            endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
            stsToken: ossInfo.securityToken,
            accessKeyId: ossInfo.accessKeyId,
            accessKeySecret: ossInfo.accessKeySecret,
            bucket: 'magicmart1' //只有此处用到所以写死，如果有出入记得和后台同步
        })
        try {
            const res = await client.multipartUpload(fileName, file, {
                progress: (p, data) => {
                    percentage && (percentage.value = (p * 100).toFixed(0) - 0)
                }
            })
            if (res && res.res && res.res.status == 200) {
                percentage && (percentage.value = 0)
                return imgSERVEURL + fileName
            } else {
                percentage && (percentage.value = 0)
                ElMessage.error('上传失败，请刷新重试！')
                return null
            }
        } catch (e) {
            percentage && (percentage.value = 0)
            ElMessage.error('上传失败，请刷新重试！')
            return null
        }
    },
    async copy(text) {
        try {
            await toClipboard(text)
            return true
        } catch (e) {
            console.error(e)
            return false
        }
    },
    getValueByKey(key, keyValue, array, valueKey) {
        if (!array || array.length === 0) return null
        let data = null
        for (let i = 0; i < array.length; i++) {
            if (array[i][key] == keyValue) {
                data = array[i]
            }
        }
        if (!data) return keyValue
        return valueKey ? data[valueKey] : data
    }
}
